package com.dingceng.demo.base.utils

import android.app.Activity
import android.content.*
import android.content.Context.*
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.location.LocationManager
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.app.NotificationManagerCompat
import com.dingceng.demo.base.BaseApplication
import com.dingceng.demo.base.REQUEST_CODE_OPEN_PUSH
import com.dingceng.demo.base.isDebug
import com.dingceng.demo.base.ui.BaseActivity
import org.json.JSONObject
import java.io.*
import java.math.BigInteger
import java.net.URL
import java.security.MessageDigest
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * 常用方法工具类
 */

private const val mTAG = "MvvmDcDemo"
fun log(msg: String) {
    log(mTAG, msg)
}

fun log(tag: String, msg: String) {
    if (isDebug) Log.e(tag, msg)
}



fun json2Map(json:String): HashMap<String, Any> {
    return json2Map(JSONObject(json))
}

fun json2Map(jsonObject:JSONObject): HashMap<String, Any> {
    val map = HashMap<String,Any>()
    jsonObject.keys().forEach { key->
        map[key] = jsonObject.get(key)
    }
    return map
}


fun toastCenter(text: String) {
    if (text.isEmpty()) return
    val topActivity = BaseApplication.getIns().getTopActivity()
    if (topActivity != null) {
        val toast = Toast.makeText(topActivity, text, Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.show()
    }
}

fun skipWeChat(context: Context){
    val intent: Intent? = context.packageManager.getLaunchIntentForPackage("com.tencent.mm")
    if (intent!=null)context.startActivity(intent)
}

fun getChannel(context: Context): String {
    try {
        val pm = context.packageManager
        val appInfo = pm.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
        val string = appInfo.metaData.getString("UMENG_CHANNEL")
        if (string != null) {
            return string
        }
    } catch (ignored: PackageManager.NameNotFoundException) {
    }

    return ""
}

fun hideSoftInput(context: Context?, v: View) {
    val imm = context?.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(v.windowToken, 0)
}


fun showSoftInput(activity: Activity?) {
    val imm = activity?.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    if (imm != null) imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}


fun String.md5(): String {
    val md = MessageDigest.getInstance("MD5")
    return BigInteger(1, md.digest(toByteArray())).toString(16).padStart(32, '0')
}



fun download(link: String, filePath: String) {
    URL(link).openStream().use { input ->
        FileOutputStream(File(filePath)).use { output ->
            input.copyTo(output)
        }
    }
}


fun copyFile(filePath: String, targetPath: String) {
    val target = File(targetPath)
    if (target.exists()) {
        target.delete()
    }
    FileOutputStream(target).use { output ->
        FileInputStream(File(filePath)).copyTo(output)
    }
}

fun getScreenHeight(context: Context): Int {
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val outMetrics = DisplayMetrics()
    wm.defaultDisplay.getMetrics(outMetrics)
    return outMetrics.heightPixels
}


fun dip2px(dipValue: Float, context: Context): Int {
    val scale = context.resources.displayMetrics.density
    return (dipValue * scale + 0.5f).toInt()
}

fun requestFocus(v: View) {
    v.isFocusable = true
    v.isFocusableInTouchMode = true
    v.requestFocus()
}




fun getVersionName(context: Context): String {
    val packageInfo = context.packageManager.getPackageInfo("com.dingceng.demo", 0)
    return packageInfo.versionName
}

fun getVersionCode(context: Context): Int {
    val packageInfo = context.packageManager.getPackageInfo("com.dingceng.demo", 0)
    return packageInfo.versionCode
}


fun getDCIMdir(): String {
    return Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera"
}


fun getBitianVideoCacheDir(): String {
    return BaseApplication.getIns().cacheDir.absolutePath + File.separator + "bitianvideo"
}

fun galleryAddPhoto(context: Context, _fileName: String, _filePath: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val out: OutputStream? = null
        try {
            val values = ContentValues()
            val resolver: ContentResolver = context.getContentResolver()
            values.put(
                MediaStore.Images.ImageColumns.DATA,
                _filePath
            ) // MediaStore.Images.ImageColumns.DATA is deprecated!
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, _fileName)
            var mine_type = "image/jpg"
            if (_fileName.contains("mp4")) mine_type = "video/mp4"
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, mine_type)
            values.put(
                MediaStore.Images.ImageColumns.DATE_TAKEN,
                System.currentTimeMillis().toString() + ""
            )
            val uri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            if (uri != null) {
                val bitmap: Bitmap = BitmapFactory.decodeFile(_filePath)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
                out!!.flush()
                out.close()
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    } else {
        Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent ->
            val f = File(_filePath)
            mediaScanIntent.data = Uri.fromFile(f)
            context.sendBroadcast(mediaScanIntent)
        }
    }
}

fun checkGPSIsOpen(context: Context): Boolean {
    val isOpen: Boolean
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
    return isOpen
}

fun isLocationEnabled(context: Context): Boolean {
    var locationMode: Int
    try {
        locationMode =
            Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)
    } catch (e: Settings.SettingNotFoundException) {
        e.printStackTrace()
        return false
    }

    return locationMode != Settings.Secure.LOCATION_MODE_OFF
}

fun openLocationSetting(context: Context) {
    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
    context.startActivity(intent)
}

fun openPushSetting(activity: Activity) {
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
            val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
            intent.putExtra("android.provider.extra.APP_PACKAGE", activity.packageName)
            activity.startActivityForResult(intent, REQUEST_CODE_OPEN_PUSH)
        }
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
            val intent = Intent()
            intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
            intent.putExtra("app_package", activity.packageName)
            intent.putExtra("app_uid", activity.applicationInfo.uid)
            activity.startActivityForResult(intent, REQUEST_CODE_OPEN_PUSH)
        }
        else -> openAppSetting(activity)
    }

}

fun openLocSetting(context: Context) {
    if (isLocationEnabled(context)) {
        openAppSetting(context)
    } else {
        openLocationSetting(context)
    }
}


fun isOpenPush(context: Context): Boolean {
    val notification = NotificationManagerCompat.from(context)
    return notification.areNotificationsEnabled()
}

fun openAppSetting(context: Context) {
    val intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    val uri = Uri.fromParts("package", context.packageName, null)
    intent.data = uri
    context.startActivity(intent)
}

fun playNotiMusic(context: Context) {
    val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val r = RingtoneManager.getRingtone(context.applicationContext, notification)
    r.play()
}


/**
 * 输入参数：source 原List ， splitItemNum 每个集合里放几个元素
sample：

INPUT
sorce : [1,2,3,4,5,6,7]
splitItemNum: 3

OUTPUT
result [1,2,3],[4,5,6],[7]1
 */
fun <T> splitList(source: List<T>?, splitItemNum: Int): List<List<T>> {
    val result = ArrayList<List<T>>()

    if (source != null && source.run { isNotEmpty() } && splitItemNum > 0) {
        if (source.size <= splitItemNum) {
            // 源List元素数量小于等于目标分组数量
            result.add(source)
        } else {
            // 计算拆分后list数量
            val splitNum = if (source.size % splitItemNum == 0) source.size / splitItemNum else source.size / splitItemNum + 1

            var value: List<T>? = null
            for (i in 0 until splitNum) {
                if (i < splitNum - 1) {
                    value = source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                } else {
                    // 最后一组
                    value = source.subList(i * splitItemNum, source.size)
                }

                result.add(value)
            }
        }
    }

    return result
}